package heman.server.controllers;

import heman.server.entities.Player;
import heman.server.entities.PlayerManager;
import heman.server.entities.TableManager;
import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.debug.Debug;
import ks.server.interfaces.IProcessServerMessage;

import org.w3c.dom.Document;

/**
 * 
 *  Controller to handle logouts. 
 *  
 *  @author Wenlong Liu
 *  */

public class LogoutController implements IProcessServerMessage {

	public boolean process(Communicator com, Message m) {
		Debug.println ("Observe logout by: " + m.getOriginator());
		String originator=m.getOriginator();
		//First check if a player is still on a table
		Player player=PlayerManager.getInstance().getPlayer(originator);
		String table=TableManager.getInstance().onTable(player);
		
		if (table!=null){
			//Construct a "leave" message
	        StringBuilder sb = new StringBuilder("<request version=\"1.0\" id=\""+m.id+
	        		"\"><leave table=\""+
	        		table+"\"/></request>");
	        
	   
	        Document d = Message.construct (sb.toString());
	        
	        // send to all clients...
	        Message r = new Message (d);
	        
	        r.setOriginator(originator);
	        
			if (!new LeaveController().process(com, r)) return false;
		}
		 // produce request.
        StringBuilder sb = new StringBuilder(Message.responseHeader(true, m.id));
        sb.append("<output><text>");
        sb.append(m.getOriginator()).append(" logged out");
        sb.append("</text></output></response>");
        Document d = Message.construct (sb.toString());
        
        // send to all clients...
        Message r = new Message (d);
        r.setOriginator(originator);
        r.setBroadcast();
        
        
        
        com.distribute(r);
      //Send logoutResponse to all online players
        //<logoutResponse player="1234"/>
        sb = new StringBuilder(Message.responseHeader(true,m.id));
        //sb.append("")
        sb.append("<logoutResponse player=\"");
        
        Player p=PlayerManager.getInstance().getPlayer(originator);
        if (p==null) return false;
        sb.append(p.getId());
        sb.append("\"/></response>");
        
        d = Message.construct(sb.toString());
        
        r = new Message (d);
        r.setOriginator(originator);
        r.setRecipient(originator);
        r.setBroadcast();
        //remove the player
        PlayerManager.getInstance().removePlayer(p);
		return com.distribute(r);
        
	}
}